package com.file.system.controller.system;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.file.system.entity.res.BaseCode;
import com.file.system.entity.res.CommonResult;
import com.file.system.entity.res.DataPage;
import com.file.system.entity.system.WebDictionary;
import com.file.system.entity.system.WebDictionaryVal;
import com.file.system.service.system.IWebDictionaryService;
import com.file.system.service.system.IWebDictionaryValService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.*;
import java.util.List;

import static cn.hutool.core.util.ObjectUtil.isNotEmpty;


/**
 * 字典值
 *
 * @author jch
 */
@RestController
@Validated
@RequestMapping("/web/dictionary/val")
public class WebDictionaryValController {

    @Autowired
    private IWebDictionaryValService service;
    @Autowired
    private IWebDictionaryService iWebDictionaryService;


    /**
     * 查询字典值分页
     *
     * @param pageIndex 页数
     * @param pageSize  每页条数
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/page/{pageIndex}/{pageSize}")
    public CommonResult<DataPage<List<WebDictionaryVal>>> page(@PathVariable
                                                               @Min(value = 1, message = "页数最小1")
                                                               Integer pageIndex,
                                                               @PathVariable
                                                               @Min(value = 1, message = "每页条数最小1")
                                                               @Max(value = 100, message = "每页条数最大100")
                                                               Integer pageSize,
                                                               @RequestBody @Validated WebDictionaryVal webDictionaryVal
    ) {
        QueryWrapper<WebDictionaryVal> query = new QueryWrapper<>();
        // 根据sort字段升序排序
        query.orderByAsc("a.sort");
        // 判断is_del字段是否为0
        query.eq("a.is_del", 0);
        // 判断pid字段是否为空，不为空则添加查询条件
        query.eq(ObjectUtil.isNotNull(webDictionaryVal.getPid()), "a.pid", webDictionaryVal.getPid());
        // 判断name字段是否为空，不为空则添加查询条件
        query.like(isNotEmpty(webDictionaryVal.getName()), "a.name", webDictionaryVal.getName());
        // 判断val字段是否为空，不为空则添加查询条件
        query.like(isNotEmpty(webDictionaryVal.getVal()), "a.val", webDictionaryVal.getVal());
        // 判断fk_dictionary_id字段是否为空，不为空则添加查询条件
        query.eq(ObjectUtil.isNotNull(webDictionaryVal.getFkDictionaryId()), "a.fk_dictionary_id", webDictionaryVal.getFkDictionaryId());

        // 执行查询，获取分页数据
        DataPage<List<WebDictionaryVal>> dp = service.page(pageIndex, pageSize, query);
        return CommonResult.ok().setResult(dp);
    }


    /**
     * 通过ids查询字典值集合
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/listByIds")
    public CommonResult<List<WebDictionaryVal>> listByIds(@RequestBody List<Long> ids) {
        //根据ids查询WebDictionaryVal列表
        List<WebDictionaryVal> list = service.listByIds(ids);
        //返回查询结果
        return CommonResult.ok().setResult(list);
    }

    /**
     * 查询所有非删除状态字典值
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/listAll")
    public CommonResult<List<WebDictionaryVal>> listAll() {
        List<WebDictionaryVal> list = service.listAll();
        return CommonResult.ok().setResult(list);
    }


    /**
     * 通过id查询字典值
     *
     * @param id 字典值id
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/id/{id}")
    public CommonResult<WebDictionaryVal> selectById(@PathVariable
                                                     @Min(value = 1, message = "id长度最小1")
                                                     Long id) {
        //查询集合
        WebDictionaryVal webDictionaryVal = service.getById(id);
        return CommonResult.ok().setResult(webDictionaryVal);
    }

    /**
     * 通过code查询字典值
     *
     * @param code 字典值code
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/code/{code}")
    public List<WebDictionaryVal> selectByCode(@PathVariable String code) {
        WebDictionary webDictionary = iWebDictionaryService.getOne(new QueryWrapper<WebDictionary>()
                .eq("a.is_del", 0)
                .eq("a.code", code)
        );
        if (webDictionary == null) {
            return null;
        }
        //查询集合
        List<WebDictionaryVal> webDictionaryValList = service.list(new QueryWrapper<WebDictionaryVal>()
                .eq("a.is_del", 0)
                .eq("a.fk_dictionary_id", webDictionary.getId())
                .orderByAsc("a.sort")
        );
        return webDictionaryValList;
    }


    /**
     * 查询字典值（懒加载）
     *
     * @param fkDictionaryId 所属字典id
     * @param pid            父级id
     * @return com.file.system.entity.res.CommonResult<com.file.system.entity.WebDictionaryVal>
     * @apiNote -
     * @author 靳春晖
     */
    @PostMapping("/pid/{fkDictionaryId}/{pid}")
    public CommonResult<WebDictionaryVal> pid(@PathVariable
                                              @NotNull(message = "所属字典id不能为空")
                                              @Min(value = 1, message = "所属字典id最小长度1")
                                              Long fkDictionaryId,
                                              @PathVariable
                                              @NotNull(message = "父级id不能为空")
                                              @Min(value = 1, message = "父级id最小长度1")
                                              Long pid) {
        //查询所有节点
        List<WebDictionaryVal> allList = service.list(new QueryWrapper<WebDictionaryVal>()
                .eq("a.is_del", 0)
                .eq("a.fk_dictionary_id", fkDictionaryId)
        );
        //查询字典值
        List<WebDictionaryVal> webDictionaryValList = service.list(new QueryWrapper<WebDictionaryVal>()
                .eq("a.is_del", 0)
                .eq("a.pid", pid)
                .eq("a.fk_dictionary_id", fkDictionaryId)
                .orderByAsc("a.sort")
        );
        //遍历字典值
        for (WebDictionaryVal val : webDictionaryValList) {
            //查询所有节点中是否有该节点
            long count = allList.stream().filter(l -> ObjectUtil.equal(val.getId(), l.getPid())).count();
            //如果有，则设置该节点为叶子节点
            if (count > 0) {
                val.setLeaf(true);
            }
        }
        return CommonResult.ok().setResult(webDictionaryValList);
    }


    /**
     * 通过id删除字典值
     *
     * @param id id
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/remove/{id}")
    public CommonResult removeById(@PathVariable
                                   @Min(value = 1, message = "id长度最小1")
                                   Long id) {
        boolean state = service.removeById(id);
        //返回
        return CommonResult.check(state);
    }


    /**
     * 通过id编辑字典值
     *
     * @param webDictionaryVal 字典值
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/updateById")
    public CommonResult<WebDictionaryVal> updateById(@RequestBody @Validated(WebDictionaryVal.update.class) WebDictionaryVal webDictionaryVal) {
        //查询
        WebDictionaryVal webDictionaryValOld = service.getById(webDictionaryVal.getId());
        //查询编码是否存在
        if (ObjectUtil.notEqual(webDictionaryValOld.getVal(), webDictionaryVal.getVal())) {
            int count = service.count(new QueryWrapper<WebDictionaryVal>()
                    .eq("a.is_del", 0)
                    .eq("a.fk_dictionary_id", webDictionaryVal.getFkDictionaryId())
                    .eq("a.val", webDictionaryVal.getVal())
            );
            if (count > 0) return CommonResult.fail(BaseCode.Common.PARAM_CODE_EXIST).setResult(webDictionaryVal);
        }
        //编辑修改
        boolean state = service.updateById(webDictionaryVal);
        //更新字典
        return CommonResult.check(state).setResult(webDictionaryVal);
    }


    /**
     * 添加字典值
     *
     * @param webDictionaryVal 字典值
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/save")
    public CommonResult<WebDictionaryVal> save(@RequestBody @Validated(WebDictionaryVal.add.class) WebDictionaryVal webDictionaryVal) {
        //查询值是否已存在
        int count = service.count(new QueryWrapper<WebDictionaryVal>()
                .eq("a.is_del", 0)
                .eq("a.fk_dictionary_id", webDictionaryVal.getFkDictionaryId())
                .eq("a.val", webDictionaryVal.getVal())
        );
        if (count > 0) return CommonResult.fail(BaseCode.Common.PARAM_CODE_EXIST).setResult(webDictionaryVal);
        //添加字典值
        boolean state = service.save(webDictionaryVal);
        //更新字典
        return CommonResult.check(state).setResult(webDictionaryVal);
    }
}

